package com.doctcloud.datacloud.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doctcloud.datacloud.entity.TransferEntity;
import com.doctcloud.datacloud.mapper.TransferEntityMapper;
import com.doctcloud.hisinfo.api.RemoteHisMedrecService;
import com.doctcloud.hisinfo.histable.domain.medrec.TransferDo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class TransferEntityService  extends ServiceImpl<TransferEntityMapper, TransferEntity> {
    private final RemoteHisMedrecService remoteHisMedrecService;
    public void syncPat(String patientId,Integer visitId) {
        log.info("开始同步患者ID：{},住院标识：{}数据...",patientId,visitId);
        long startTime = System.currentTimeMillis();
        try {
            // 1. 从远程服务获取全量价表信息
            List<TransferDo> remoteTransfers = remoteHisMedrecService.listTransferByPat(patientId, visitId);
            // 优化点：使用 String.format 或 SLF4J 的占位符来打印日志
            if (remoteTransfers == null || CollectionUtils.isEmpty(remoteTransfers)) {
                String errorMsg = String.format("获取患者ID:%s,住院标识:%s 的转科记录信息失败，服务已降级。", patientId, visitId);
                log.error("从远程服务获取转科记录失败或返回为空，同步任务终止。原因: {}", errorMsg);
                return;
            }
            log.info("从远程服务获取到 {} 个转科记录信息。", remoteTransfers.size());

            // 2. 将 Do 转换为 Entity
            List<TransferEntity> entitiesToUpsert = remoteTransfers.stream()
                    .filter(doObj ->
                            doObj.getPatientId() != null && !doObj.getPatientId().trim().isEmpty() &&
                                    doObj.getVisitId() != null &&
                                    doObj.getDeptStayed() != null && !doObj.getDeptStayed().trim().isEmpty() &&
                                    doObj.getDoctorInCharge() != null && !doObj.getDoctorInCharge().trim().isEmpty()
                    )
                    .map(doObj -> {
                        TransferEntity entity = new TransferEntity();
                        entity.setPatientId(doObj.getPatientId());
                        entity.setVisitId(doObj.getVisitId());
                        entity.setDeptStayed(doObj.getDeptStayed());
                        entity.setAdmissionDateTime(doObj.getAdmissionDateTime());
                        entity.setDischargeDateTime(doObj.getDischargeDateTime());
                        entity.setDeptTransferedTo(doObj.getDeptTransferedTo());
                        entity.setDoctorInCharge(doObj.getDoctorInCharge());

                        return entity;
                    })
                    .collect(Collectors.toList());

            if (entitiesToUpsert.isEmpty()) {
                log.info("没有需要同步的住院费用明细记录。");
                return;
            }
            // 3. 执行批量UPSERT操作
            log.info("准备执行批量UPSERT操作...");
            int affectedRows = baseMapper.batchUpsert(entitiesToUpsert);

            log.info("同步完成。总耗时：{} ms。数据库受影响的行数: {}",
                    System.currentTimeMillis() - startTime, affectedRows);
        } catch (Exception e) {
            log.error("同步住院费用明细时发生异常: ", e);
            // 在这里可以添加异常处理逻辑，例如告警、回滚事务等
        }
    }
}
